// backend/controllers/menuController.js
const db = require('../config/db');

// Get all menu items
exports.getAllMenuItems = async (req, res) => {
    try {
        const [rows] = await db.query('SELECT * FROM MenuItems ORDER BY category, item_name');
        res.json(rows);
    } catch (err) {
        console.error('获取菜单项列表错误:', err);
        res.status(500).json({ error: '获取菜单项列表失败' });
    }
};

// Add a new menu item
exports.addMenuItem = async (req, res) => {
    try {
        const { item_name, price, category } = req.body;

        // Check if item name already exists
        const [existingItem] = await db.query(
            'SELECT * FROM MenuItems WHERE item_name = ?',
            [item_name]
        );

        if (existingItem.length > 0) {
            return res.status(400).json({
                error: '菜单项名称已存在',
                message: `菜单项 ${item_name} 已存在，请使用其他名称`
            });
        }

        const [result] = await db.query(
            'INSERT INTO MenuItems (item_name, price, category) VALUES (?, ?, ?)',
            [item_name, price, category]
        );

        res.status(201).json({
            message: '菜单项添加成功',
            itemId: result.insertId
        });

    } catch (err) {
        if (err.code === 'ER_DUP_ENTRY') {
            console.error(`菜单项名称冲突: ${item_name}`);
            res.status(400).json({
                error: '菜单项名称已存在',
                message: `菜单项 ${item_name} 已存在，请使用其他名称`
            });
        } else {
            console.error('添加菜单项错误:', err);
            res.status(500).json({
                error: '添加菜单项失败',
                details: err.message
            });
        }
    }
};

// Bulk import menu items
exports.bulkImportMenuItems = async (req, res) => {
    try {
        const menuItems = req.body;

        if (!Array.isArray(menuItems) || menuItems.length === 0) {
            return res.status(400).json({ error: '无效的菜单项数据' });
        }

        // Check for duplicate item names
        const itemNames = menuItems.map(item => item.item_name);
        const [existingItems] = await db.query(
            'SELECT item_name FROM MenuItems WHERE item_name IN (?)',
            [itemNames]
        );

        const existingNames = existingItems.map(item => item.item_name);
        const duplicates = menuItems.filter(item => existingNames.includes(item.item_name));

        if (duplicates.length > 0) {
            const duplicateNames = duplicates.map(r => r.item_name).join(', ');
            return res.status(400).json({
                error: '存在重复菜单项名称',
                message: `以下菜单项名称已存在: ${duplicateNames}`,
                duplicates
            });
        }

        // Build values for bulk insert
        const values = menuItems.map(item => [
            item.item_name,
            item.price,
            item.category || null // Allow null for category if not provided
        ]);

        const [result] = await db.query(
            'INSERT INTO MenuItems (item_name, price, category) VALUES ?',
            [values]
        );

        res.status(201).json({
            message: `成功导入${result.affectedRows}个菜单项`,
            importedCount: result.affectedRows
        });

    } catch (err) {
        if (err.code === 'ER_DUP_ENTRY') {
            console.error('批量导入菜单项名称冲突:', err);
            res.status(400).json({
                error: '存在重复菜单项名称',
                message: '导入文件中包含已存在的菜单项名称'
            });
        } else {
            console.error('批量导入菜单项错误:', err);
            res.status(500).json({
                error: '批量导入失败',
                details: err.message
            });
        }
    }
};